/*
 * $Id: AbstractServerGraphTag.java 41 2013-01-08 04:03:56Z rob@patientsknowbest.com $ 
 */
package com.representqueens.web.tags.spark;

/*
 * 
 * Copyright 2007 Larry Ogrodnek
 * Copyright 2011 Rob Whelan, Patients Know Best
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.representqueens.spark.DataPoint;
import com.representqueens.util.StringUtils;

/**
 * @author Larry Ogrodnek <larry@cheesesteak.net>
 * @author Rob Whelan <rob@patientsknowbest.com>
 * @version $Revision: 41 $ $Date: 2013-01-08 04:03:56 +0000 (Tue, 08 Jan 2013) $
 */
public abstract class AbstractServerGraphTag extends AbstractGraphTag {
    private static final String DEFAULT_PATH = "/spark";

    private String path;

    public String getPath() {
    	return this.path;
    }

    public void setPath(final String path) {
    	this.path = path;
    }

    public String getRealPath() {
		final Object o = this.pageContext.findAttribute("sparkPath");
	
		if (o instanceof String) {
		    return convertPath(o.toString());
		}
	
		return convertPath((this.path == null ? DEFAULT_PATH : this.path));
    }

    private String convertPath(final String s) {
		final String c = ((HttpServletRequest) this.pageContext.getRequest())
			.getContextPath();
		return String.format("%s%s", c, s);
    }

    protected String getQueryParams() {
    	final StringBuilder sb = new StringBuilder();

    	final String[] n = new String[] { "color", "background", "rangeColor", "width", "height",
    			"spacing", "output", "forceYMin", "forceYMax", "forceXMin", "forceXMax" };
    	final String[] p = new String[] { getColor(), getBackground(), getRangeColor(), getWidth(), getHeight(),
    			getSpacing(), getOutput(), getForceYMin(), getForceYMax(), getForceXMin(), getForceXMax() };

    	try {
    		for (int i = 0; i < n.length; i++) {
    			if (!StringUtils.isEmpty(p[i])) {
    				sb.append("&").append(n[i]).append("=")
    				.append(URLEncoder.encode(p[i], "UTF-8"));
    			}
    		}
    	} catch (final UnsupportedEncodingException uee) {
    		uee.printStackTrace(); // won't happen...
    	}

    	final List<DataPoint> data = getData();

    	if (data != null && data.size() > 0) {
    		sb.append("&data=");
    		sb.append(StringUtils.toString(data));
    	}

    	return sb.toString();
    }
}
